package com.halko.PR.pr.detect;


import static org.bytedeco.javacpp.opencv_core.CV_32FC1;
import static org.bytedeco.javacpp.opencv_imgproc.resize;

import java.util.Vector;

import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.Rect;
import org.bytedeco.javacpp.opencv_core.Size;
import org.bytedeco.javacpp.opencv_ml.CvSVM;

import com.halko.PR.pr.svm.Features;
import com.halko.PR.pr.svm.SVMCallback;

/**
 * 车牌判断
 * @author halko
 * @create 2021-03-25 21:06
 */
public class PlateJudgement {
    private CvSVM svm = new CvSVM();

    /**
     * 用于从车牌的image生成svm的训练特征features
     */
    private SVMCallback features = new Features();

    private String path = "res/model/svm.xml";

    /**
     * 对多幅候选车牌进行SVM判断
     *
     * @param intVec
     * @param resultVec
     * @return
     */
    public int plateJudge(Vector<Mat> intVec, Vector<Mat> resultVec) {
        for (int i = 0; i < intVec.size(); i++) {
            Mat inMat = intVec.get(i);
            if (plateJudge(inMat) == 1) {
                resultVec.add(inMat);
            } else {
                int w = inMat.cols();
                int h = inMat.rows();
                Mat tmpDes = inMat.clone();
                Mat tmpMat = new Mat(inMat,
                        new Rect((int) (w * 0.05), (int) (h * 0.1), (int) (w * 0.9), (int) (h * 0.8)));
                resize(tmpMat, tmpDes, new Size(inMat.size()));

                if (plateJudge(tmpDes) == 1) {
                    resultVec.add(inMat);
                }
            }
        }

        return 0;
    }

    /**
     * 对单幅候选车图进行SVM判断
     *
     * @param inMat
     * @return
     */
    private int plateJudge(Mat inMat) {
        Mat features = this.features.getHistogramFeatures(inMat);

        // 通过直方图均衡化后的彩色图进行预测
        Mat p = features.reshape(1, 1);
        p.convertTo(p, CV_32FC1);

        // 对图片进行预测
        float res = svm.predict(p);

        return (int) res;
    }


    public PlateJudgement() {
        loadModel();
    }

    public void loadModel() {
        loadModel(path);
    }

    public void loadModel(String s) {
        svm.clear();
        svm.load(s, "svm");
    }

}
